﻿using Microsoft.SharePoint;
using System;
using System.Collections;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI.WebControls.WebParts;

namespace vwpCustomUpload.VisualWebPart1
{
    [ToolboxItemAttribute(false)]
    public partial class CustomUpload : WebPart
    {

        private string _listName;
        
          [System.Web.UI.WebControls.WebParts.WebBrowsable(true),
          System.Web.UI.WebControls.WebParts.WebDisplayName("Enter List Name"),
          System.Web.UI.WebControls.WebParts.WebDescription(""),
          System.Web.UI.WebControls.WebParts.Personalizable(
          System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared),
          System.ComponentModel.Category("Custom Upload Properties"),
          System.ComponentModel.DefaultValue("Admin")]
          public string ListName
         {
            get { return _listName; }
            set { _listName = value; }
         }

        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling using
        // the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public CustomUpload()
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //int itemID = DeleteExistingAttachments();

                //if (itemID == 0)
                //{
                //using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
                //{
                //SPWeb web = site.RootWeb;
                //web.AllowUnsafeUpdates = true;
                //SPList SPLData = web.Lists["FormTemp"];
                //SPListItem item = SPLData.Items.Add();
                //item["Title"] = web.CurrentUser.Name + " staged Attachments";
                //txtObject.Text = web.CurrentUser.Name + " staged Attachments";
                //using (DisableItemEventsScope scope = new DisableItemEventsScope())
                //{
                //    item.Update();
                //}
                //hdnItemID.Value = item.ID.ToString();
                //web.AllowUnsafeUpdates = false;
                //}
                //}
                //else
                //{
                //using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
                //{
                //    SPWeb web = site.RootWeb;
                //    txtObject.Text = web.CurrentUser.Name + " staged Attachments";
                //}
                //hdnItemID.Value = itemID.ToString();
                //}
                //}
                //string urlFormat = "/_layouts/AttachFile.aspx?ListId={0}&ItemID={1}";

                ////Procedure {1049EAE4-FA67-4648-A47F-6A4BA7BAE96F}
                ////formTemp  {83DFB3CB-4FEB-4FED-9D9C-0539DE8AC2A5}
                //string url = string.Format(urlFormat, "{83DFB3CB-4FEB-4FED-9D9C-0539DE8AC2A5}", hdnItemID.Value);
                //hdnURL.Value = url;
                //btnAttachFile.Disabled = false;
            }
        }

        //private int DeleteExistingAttachments()
        //{
        //    int itemId = 0;
        //    // Follow the steps to delete list item attachment from your sharepoint list.
        //    // Create new instance of site with your current application
        //    SPSecurity.RunWithElevatedPrivileges(delegate()
        //    {
        //        using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
        //        {
        //            // Create new web instance and open web for current application
        //            SPWeb web = site.RootWeb;
        //            web.AllowUnsafeUpdates = true;
        //            // Create new list object and get your list
        //            if (!string.IsNullOrEmpty(ListName))
        //            {
        //                SPList SPLData = web.Lists[ListName];
        //                // Create new query object to hold query which fetches list item of the list
        //                SPQuery spMyQuery = new SPQuery();
        //                // Assign query with value to it in ID field of the list item
        //                spMyQuery.Query = "<Where><Eq><FieldRef Name='Author'/><Value Type='Integer'><UserID Type='Integer' /></Value></Eq></Where>";
        //                SPListItemCollection collection = SPLData.GetItems(spMyQuery);
        //                if (collection.Count > 0)
        //                {
        //                    SPListItem listItem = collection[0];
        //                    itemId = Convert.ToInt32(listItem["ID"]);
        //                    ArrayList al = new ArrayList();
        //                    if (listItem.Attachments != null && listItem.Attachments.Count > 0)
        //                    {
        //                        foreach (string fileName in listItem.Attachments)
        //                        {
        //                            al.Add(fileName);
        //                        }

        //                        foreach (string fileName in al)
        //                        {
        //                            listItem.Attachments.Delete(fileName);

        //                            using (DisableItemEventsScope scope = new DisableItemEventsScope())
        //                            {
        //                                listItem.Update();
        //                            }
        //                        }
        //                    }
        //                }
        //                web.AllowUnsafeUpdates = false;
        //            }
        //        }
        //  });
        //  return itemId;
        //}

        //private int DeleteExistingAttachment(SPListItem targetItem)
        //{
        //    int itemId = 0;
        //    // Follow the steps to delete list item attachment from your SOURCE sharepoint list.
        //    // Create new instance of site with your current application
        //    SPSecurity.RunWithElevatedPrivileges(delegate()
        //    {
        //        using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
        //        {
        //            // Create new web instance and open web for current application
        //            SPWeb web = site.RootWeb;
        //            web.AllowUnsafeUpdates = true;
        //            // Create new list object and get your list
        //            SPList SPLData = web.Lists["FormTemp"];
        //            // Create new query object to hold query which fetches list item of the list
        //            SPQuery spMyQuery = new SPQuery();
        //            // Assign query with value to it in ID field of the list item
        //            spMyQuery.Query = "<Where><Eq><FieldRef Name='Author'/><Value Type='Integer'><UserID Type='Integer' /></Value></Eq></Where>";
        //            SPListItemCollection collection = SPLData.GetItems(spMyQuery);
        //            if (collection.Count > 0)
        //            {
        //                SPListItem listItem = collection[0];
        //                itemId = Convert.ToInt32(listItem["ID"]);
        //                if (listItem.Attachments != null && listItem.Attachments.Count > 0)
        //                {
        //                    ArrayList al = new ArrayList();
        //                    foreach (string fileName in listItem.Attachments)
        //                    {
        //                        al.Add(fileName);
                                
        //                    }

        //                    SPAttachmentCollection colAttachments = targetItem.Attachments;
        //                    bool boolAttachmentFound = false;
        //                    foreach (string fileName in al)
        //                    {
        //                        for (int i = 0; i < colAttachments.Count; i++)
        //                        {
        //                            if (fileName == colAttachments[i]) { boolAttachmentFound = true; }
        //                        }

        //                        if (boolAttachmentFound)
        //                        {
        //                            targetItem.Attachments.Delete(fileName);
        //                            using (DisableItemEventsScope scope = new DisableItemEventsScope())
        //                            {
        //                                targetItem.Update();
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //            web.AllowUnsafeUpdates = false;
        //        }
        //    });
        //    return itemId;
        //}
        /// <summary>
        ///
        /// </summary>
        /// <param name="sourceItem"></param>
        /// <param name="targetItem"></param>
        //private void CopyAttachments(SPListItem sourceItem, SPListItem targetItem)
        //{
        //    try
        //    {
        //        //get the folder with the attachments for the source item
        //        string parentOriginalListName = sourceItem.ParentList.RootFolder.Url.Replace("Lists/", "");
        //        SPFolder sourceItemAttachmentsFolder =
        //            sourceItem.Web.Folders["Lists"].SubFolders[parentOriginalListName].SubFolders["Attachments"].SubFolders[sourceItem.ID.ToString()];
        //        //Loop over the attachments, and add them to the target item
        //        foreach (SPFile file in sourceItemAttachmentsFolder.Files)
        //        {
        //            byte[] binFile = file.OpenBinary();
        //            targetItem.Attachments.AddNow(file.Name, binFile);
        //        }
        //    }
        //    catch { }
        //    finally
        //    {
        //        //sourceItem.Web.Dispose();
        //    }
        //}

        //protected void btnSave_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        SPWeb spWeb = SPContext.Current.Web;
        //        SPList spTargetList = spWeb.Lists["FormList"];
        //        SPListItem targetItem = spTargetList.GetItemById(Convert.ToInt32(this.Page.Request.QueryString["ID"].ToString()));
        //        //SPList spListTemp = spWeb.Lists["FormTemp"];
        //        //SPListItem sourceItem = spListTemp.GetItemById(Convert.ToInt32(hdnItemID.Value));
        //        DeleteExistingAttachment(targetItem);
        //        //CopyItem(sourceItem, targetItem);
        //        //CopyAttachments(sourceItem, targetItem);
        //        DeleteExistingAttachments();
        //        Page.Response.Redirect(this.Page.Request.Url.ToString());
        //    }
        //    catch (Exception ex)
        //    {
        //        Page.Response.Write(ex.Message);
        //    }
        //}

        protected void btnSave1_Click(object sender, EventArgs e)
        {
            try
            {
                SPWeb spWeb = SPContext.Current.Web;
                SPList spTargetList = spWeb.Lists[ListName];
                SPListItem targetItem = spTargetList.GetItemById(Convert.ToInt32(this.Page.Request.QueryString["ID"].ToString()));
                DeleteExistingAttachmentFromTarget(targetItem);
                SaveAttachments(targetItem);
                //DeleteExistingAttachments();
                Page.Response.Redirect(this.Page.Request.Url.ToString());
            }
            catch (Exception ex)
            {
                Page.Response.Write(ex.Message);
            }
        }

        private void SaveAttachments(SPListItem targetItem)
        {
            try
            {
                //get the folder with the attachments for the source item
                //string parentOriginalListName = sourceItem.ParentList.RootFolder.Url.Replace("Lists/", "");
                //SPFolder sourceItemAttachmentsFolder =
                //    sourceItem.Web.Folders["Lists"].SubFolders[parentOriginalListName].SubFolders["Attachments"].SubFolders[sourceItem.ID.ToString()];
                //Loop over the attachments, and add them to the target item
                foreach (HttpPostedFile file in fu1.PostedFiles)
                {
                    System.IO.Stream myStream;
                    Int32 fileLen;
                    StringBuilder displayString = new StringBuilder();
                              
                    // Initialize the stream to read the uploaded file.
                    myStream = file.InputStream;
        
                    // Get the length of the file.
                    fileLen = file.ContentLength;

                    // Create a byte array to hold the contents of the file.
                    Byte[] binFile = new Byte[fileLen];

                    // Read the file into the byte array.
                    myStream.Read(binFile, 0, fileLen);

                    targetItem.Attachments.AddNow(file.FileName, binFile);
                }
            }
            catch { }
            finally
            {
            }
        }

        private void DeleteExistingAttachmentFromTarget(SPListItem targetItem)
        {
            SPAttachmentCollection colAttachments = targetItem.Attachments;
            if (fu1.PostedFile != null)
            {
                foreach (HttpPostedFile eachPostedFile in fu1.PostedFiles)
                {
                    string fileName = eachPostedFile.FileName;
                    bool boolAttachmentFound = false;
                    for (int i = 0; i < colAttachments.Count; i++)
                    {
                        if (fileName == colAttachments[i]) 
                        { 
                            boolAttachmentFound = true; 
                        }
                    }

                    if (boolAttachmentFound)
                    {
                        targetItem.Attachments.Delete(fileName);
                        using (DisableItemEventsScope scope = new DisableItemEventsScope())
                        {
                            targetItem.Update();
                        }
                        boolAttachmentFound = false;
                    }
                }
            }
        }
    }
}
